package com.atguigu.gmall.realtime.app.dwd.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseApp;
import com.atguigu.gmall.realtime.commont.Constant;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SideOutputDataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author lzc
 * @Date 2023/4/22 14:08
 */
public class DwdBaseLog extends BaseApp {
    
    private final String START = "start";
    private final String DISPLAY = "display";
    private final String ACTION = "action";
    private final String ERR = "err";
    private final String PAGE = "page";
    
    public static void main(String[] args) {
        new DwdBaseLog().init(
            30001,
            2,
            "DwdBaseLog",
            Constant.TOPIC_ODS_LOG  // shift + ctrl + u 大小写切换
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
    
        // 1. 数据清洗
        SingleOutputStreamOperator<String> etledStream = etl(stream);
        // 2. 新老客户标记的纠正 有可能会把老用户识别为新用户
        SingleOutputStreamOperator<JSONObject> validatedStream = validateNewOrOld(etledStream);
        // 3. 分流
        Map<String, DataStream<JSONObject>> streams = splitStream(validatedStream);
        
        // 4. 写出到 kafka
        writeToKafka(streams);
    }
    
    private void writeToKafka(Map<String, DataStream<JSONObject>> streams) {
        streams.get(PAGE).map(JSONAware::toJSONString).sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_PAGE));
//        streams.get(PAGE).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSinkFunction(Constant.TOPIC_DWD_TRAFFIC_PAGE));
        
        streams.get(ERR).map(JSONAware::toJSONString).sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ERR));
        streams.get(DISPLAY).map(JSONAware::toJSONString).sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_DISPLAY));
        streams.get(START).map(JSONAware::toJSONString).sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_START));
        streams.get(ACTION).map(JSONAware::toJSONString).sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ACTION));
       
    
    }
    
    private Map<String, DataStream<JSONObject>> splitStream(SingleOutputStreamOperator<JSONObject> stream) {
        OutputTag<JSONObject> displayTag = new OutputTag<JSONObject>("display", TypeInformation.of(JSONObject.class));
        OutputTag<JSONObject> actionTag = new OutputTag<JSONObject>("action"){};
        OutputTag<JSONObject> errTag = new OutputTag<JSONObject>("err"){};
        OutputTag<JSONObject> pageTag = new OutputTag<JSONObject>("page"){};
    
        //OutputTag<ArrayList<Integer>> a = new OutputTag<ArrayList<Integer>>("display", TypeInformation.of(new TypeHint<ArrayList<Integer>>() {}));
        // 1 -> 5
        // 技术: 测输出流
        // 主流: 启动日志
        // 4 个测输出流: 其他 4 个日志
        SingleOutputStreamOperator<JSONObject> startStream = stream
            .process(new ProcessFunction<JSONObject, JSONObject>() {
                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<JSONObject> out) throws Exception {
                    JSONObject common = obj.getJSONObject("common");
                    Long ts = obj.getLong("ts");
    
    
                    JSONObject start = obj.getJSONObject("start");
                    if (start != null) { // 是启动日志
                        out.collect(obj);
                        
                    }
                    
                    // 2. 曝光
                    JSONArray displays = obj.getJSONArray("displays");
                    if (displays != null) {
                        for (int i = 0; i < displays.size(); i++) {
                            JSONObject display = displays.getJSONObject(i);
                            display.putAll(common);
                            display.put("ts", ts);
                            ctx.output(displayTag, display);
                        }
    
                        obj.remove("displays");   // 移除 displays 这个 key, 因为后面的日志处理用不上
                        
                    }
                    
                    // 3. 活动
                    JSONArray actions = obj.getJSONArray("actions");
                    if (actions != null) {
                        for (int i = 0; i < actions.size(); i++) {
                            JSONObject action = actions.getJSONObject(i);
                            action.putAll(common);
                            ctx.output(actionTag, action);
                        }
        
                        obj.remove("actions");
        
                    }
                    
                    // 4. 错误
                    JSONObject err = obj.getJSONObject("err");
                    if (err != null) {
                        ctx.output(errTag, obj);
                        obj.remove("err");
                    }
                    
                    // 5. page
                    JSONObject page = obj.getJSONObject("page");
                    if (page != null) {
                        ctx.output(pageTag, obj);
                    }
                }
            });
    
        SideOutputDataStream<JSONObject> displayStream = startStream.getSideOutput(displayTag);
        SideOutputDataStream<JSONObject> actionStream = startStream.getSideOutput(actionTag);
        SideOutputDataStream<JSONObject> errStream = startStream.getSideOutput(errTag);
        SideOutputDataStream<JSONObject> pageStream = startStream.getSideOutput(pageTag);
        
        // 数组 list Tuple5
        // map: string->stream
        Map<String, DataStream<JSONObject>> streams = new HashMap<>();
        streams.put(START, startStream);
        streams.put(DISPLAY, displayStream);
        streams.put(ACTION, actionStream);
        streams.put(ERR, errStream);
        streams.put(PAGE, pageStream);
        return streams;
    
    
    }
    
    private SingleOutputStreamOperator<JSONObject> validateNewOrOld(SingleOutputStreamOperator<String> stream) {
       return stream
            .map(JSON::parseObject)
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
            .map(new RichMapFunction<JSONObject, JSONObject>() {
    
                private ValueState<String> firstVisitDateState;
    
                @Override
                public void open(Configuration parameters) throws Exception {
                    firstVisitDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("firstVisitDate", String.class));
                }
    
                @Override
                public JSONObject map(JSONObject obj) throws Exception {
                    JSONObject common = obj.getJSONObject("common");
                    String isNew = common.getString("is_new");
                    Long ts = obj.getLong("ts");
                    String today = AtguiguUtil.tsToDate(ts);
    
                    String firstVisitDate = firstVisitDateState.value();
    
                    if ("1".equals(isNew)) {  // isNew==1
                        if (firstVisitDate == null) { // 没有访问过, 这次是第一天的第一次
                            // 把今天存入到状态中
                            firstVisitDateState.update(today);
                        }else{
                            if (!today.equals(firstVisitDate)) {
                                // 是一个老用户, 需要把 is_new 从 1->0
                                common.put("is_new", "0");
                            }
                        }
                    }else{
                        // 如果是老用户, 并且状态是 null,则为了防止以后出错,把状态更新为昨天
                        if (firstVisitDate == null) {
                            firstVisitDateState.update(AtguiguUtil.tsToDate(ts - 24 * 60 * 60 * 1000));
                        }
                    }
                    return obj;
                }
            });
        /*
        纠正原理:
            转态
                原始状态
                管理状态
                    算子
                        只和算子的并行度有关, 可以用在任何的算子上, 大部分用在 source 和 sink 上
                        列表
                        联合列表
                        广播状态
                    键控状态
                        只能用在 KeyedStream, 每个 key 都有自己的状态
                        
                        value
                        list
                        reduce
                        aggregate
                        map
            
            状态中存入一个首次访问的日期
                mid_1   首次 2023-03-19
                    每来一条数据,判断这条数据日期和2023-03-19  是否一致, 如果一致是新用户
                    如果不一致,就一定是老用户
                    
              
            is_new=1
                state == null
                    新用户的,第一条访问记录
                    把日期存入到状态中
                state != null
                    日期和状态是否一致
                    
                    一致:
                        不需要任何操作
                    不一致:
                        is_new=0
        
         */
    }
    
    private SingleOutputStreamOperator<String> etl(DataStreamSource<String> stream) {
      return  stream.filter(new FilterFunction<String>() {
            @Override
            public boolean filter(String value) throws Exception {
                try {
                    JSONObject obj = JSON.parseObject(value);
                    return obj.getJSONObject("common") != null;
                } catch (Exception e) {
                    System.out.println("数据格式不对: " + value);
                    
                    return false;
                }
            }
        });
    }
}
/*
1. 读取 ods_log 数据

2. etl 清洗

4. 分流
    手动分流
        if判断

5. 不同的流把数据写入到不同的 topic 中

 */